<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="queryParams.status" placeholder="请选择" style="width: 100px" clearable>
          <el-option
            v-for="dict in dict.type.business_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-upload2" size="mini" @click="handleOnline">上架</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-download" size="mini" @click="handleOffline">下架</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="videoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" width="50"/>
      <el-table-column label="标题" align="center" prop="title" width="200"/>
      <el-table-column label="封面图" align="center" prop="url" :show-overflow-tooltip="true"  width="150">
        <template slot-scope="scope">
          <el-image @click="bigImg(`${scope.row.url}`)"
            style="width: 120px; height: 120px; margin-bottom:-4px"
            :src="scope.row.url"
            :preview-src-list="srcList"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column label="首页是否显示" align="center" key="ifIndex" width="100">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.ifIndex"
                active-value="1"
                inactive-value="0"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.business_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" width="50"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        <el-button size="mini" type="text" icon="el-icon-upload" @click="handleSetImg(scope.row)">设置封面图</el-button>
        <el-button v-if="scope.row.status !== '1'" size="mini" type="text" icon="el-icon-upload2" @click="handleOnline(scope.row)">上架</el-button>
        <el-button v-if="scope.row.status === '1'" size="mini" type="text" icon="el-icon-download" @click="handleOffline(scope.row)">下架</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      <!-- 添加或修改对话框 -->
      <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="1000px" append-to-body>
        <div class="product_info">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-row>
            <el-col :span="23">
              <el-form-item label="视频标题" prop="title">
                <el-input v-model="form.title" placeholder="请输入视频标题" :maxlength="30" show-word-limit/>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="23">
              <el-form-item label="视频内容" prop="content">
                <myeditor v-model="form.content" v-if="open" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :span="18">
              <el-form-item label="视频文件" prop="videoUrl">
                <video ref="videoRef" :src="basePath + form.videoUrl"  width="460" height="300" controls></video>
              </el-form-item> 
            </el-col>
            <el-col :span="6">
              <el-button
                  v-if="form.videoUrl === undefined"
                  type="info"
                  plain
                  icon="el-icon-upload"
                  size="mini"
                  @click="handleImport"
                >上传视频</el-button>
            </el-col>
          </el-row>  
          <el-row>
            <el-col :span="23">
              <el-form-item label="显示排序" prop="sort">
                <el-input-number v-model="form.sort" controls-position="right" :min="0" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
  
  <!--视频上传-->
  <el-dialog :title="upload.title2" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".mp4, .avi, .rmvb"
        :headers="upload.headers"
        :action="upload.url"
        :disabled="upload.isUploading"
        :on-error="handleUploadError"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <p>仅允许导入mp4、avi、rmvb格式的视频文件</p>
          <p>大小不超过 <b style="color: #f56c6c">100MB</b></p>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!--设置封面图-->
    <el-dialog :title="title" :visible.sync="options.open" width="900px" append-to-body @opened="modalOpened"  @close="closeDialog">
      <el-row>
        <el-col :xs="24" :md="12" :style="{height:setHeight+'px'}">
          <vue-cropper
            ref="cropper"
            :img="options.img"
            :info="true"
            :autoCrop="options.autoCrop"
            :autoCropWidth="options.autoCropWidth"
            :autoCropHeight="options.autoCropHeight"
            :fixedBox="options.fixedBox"
            :outputType="options.outputType"
            @realTime="realTime"
            v-if="options.visible"
          />
        </el-col>
        <el-col :xs="24" :md="12" :style="{height:setHeight+'px'}">
          <div class="logo-upload-preview">
            <img :src="previews.url" :style="previews.img" />
          </div>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :lg="2" :sm="3" :xs="3">
          <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
            <el-button size="small">
              选择
              <i class="el-icon-upload el-icon--right"></i>
            </el-button>
          </el-upload>
        </el-col>
        <el-col :lg="{span: 1, offset: 2}" :sm="2" :xs="2">
          <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
        </el-col>
        <el-col :lg="{span: 1, offset: 1}" :sm="2" :xs="2">
          <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
        </el-col>
        <el-col :lg="{span: 2, offset: 6}" :sm="2" :xs="2">
          <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import {listVideo,delVideo,upateIfIndex,getVideo,addVideo,updateVideo,uploadFileImg,batchUpdateStatus,updateStatus} from "@/api/product/video";
import { getToken } from "@/utils/auth";
import { VueCropper } from "vue-cropper";
import { debounce } from '@/utils'

export default {
  name: "Video",
  dicts: [
    'business_status',
  ],
  components: { 
    VueCropper,
    seoDetail: () => import('@/views/content/seo/detail'),
  },
  props: {
    setWidth:{
      type:Number,
      default:763
    },
    setHeight:{
      type:Number,
      default:480
    },
  },
  data() {
    return {
      basePath: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 公告表格数据
      videoList: [],
      // 选中数组
       ids: [],
      // 非多个禁用
      multiple: true,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: undefined,
        status: undefined,
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title2: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/product/video/uploadVideo"
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "视频标题不能为空", trigger: "blur" }
        ],
        content: [
          { required: true, message: "视频内容不能为空", trigger: "blur" }
        ],
        videoUrl: [
          { required: true, message: "视频不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      },
      srcList:["https://fuss10.elemecdn.com/8/27/f01c15bb73e1ef3793e64e6b7bbccjpeg.jpeg"],
      options: {
        id: undefined,
        img: undefined,
        // 是否显示弹出层
        open: false,
        // 是否显示cropper
        visible: false,
        // 弹出层标题
        title: "修改",
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: this.setWidth / 2, // 默认生成截图框宽度
        autoCropHeight: this.setHeight / 2, // 默认生成截图框高度
        fixedBox: true, // 固定截图框大小 不允许改变
        outputType:"png" // 默认生成截图为PNG格式
      },
      previews: {},
      resizeHandler: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询视频列表 */
    getList() {
      this.loading = true;
      this.videoList = [];
      listVideo(this.queryParams).then(response => {
        let sourceVideoList = response.rows;
        if (sourceVideoList !== undefined && sourceVideoList.length > 0) {
          for (let i = 0; i < sourceVideoList.length; i++) {
            const video = sourceVideoList[i];
            video['url'] = process.env.VUE_APP_BASE_API + video['url'];
            this.videoList.push(video);
          }
        }
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        content: undefined,
        videoUrl: undefined,
        sort: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
      /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加视频";
      this.form.videoUrl= '';
    },
      /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id 
      getVideo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改视频";
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
      handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 删除按钮操作 */
    handleDelete(row) {
    const id = row.id || this.ids;
    this.$modal.confirm('是否确认删除参数编号为"' + id + '"的数据项？').then(function() {
        return delVideo(id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
     },

    // 是否在首页显示开关修改
    handleStatusChange(row) {
      let text = row.ifIndex === "1" ? "是" : "否";
      this.$modal.confirm('是否要在首页显示"' + text ).then(function() {
        if (row.ifIndex === '1' && row.status !== '1') {
          this.$modal.msgError("设置首页展示必须是上架状态");
          return;
        }
        return upateIfIndex(row.id, row.ifIndex);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.ifIndex = row.ifIndex === "0" ? "1" : "0";
      });
    },
     /** 提交按钮 */
     submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateVideo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addVideo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
     },

     //视频上传
     handleImport() {
      this.upload.title2 = "视频上传";
      this.upload.open = true;
    },
    // 上传失败
    handleUploadError(err) {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "修改结果", { dangerouslyUseHTMLString: true });
      this.form.videoUrl = response.videoUrl;
      this.upload.open = false;
      this.upload.isUploading = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    /*getText(text) {
      this.form.remark = text;
    },*/
    bigImg(url) {
      this.srcList[0] = url;
    },
    /**设置文描 */
    handleSetImg(row) {
      this.options.open = true;
      this.options.id = row.id;
    },
    // 打开弹出层结束时的回调
    modalOpened() {
      this.options.visible = true;
      if (!this.resizeHandler) {
        this.resizeHandler = debounce(() => {
          this.refresh()
        }, 100)
      }
      window.addEventListener("resize", this.resizeHandler)
    },
    // 刷新组件
    refresh() {
      this.$refs.cropper.refresh();
    },
    // 覆盖默认的上传行为
    requestUpload() {
    },
    // 向左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    // 向右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    // 图片缩放
    changeScale(num) {
      num = num || 1;
      this.$refs.cropper.changeScale(num);
    },
    // 上传预处理
    beforeUpload(file) {
      if (file.type.indexOf("image/") == -1) {
        this.$modal.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
      } else {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => {
          this.options.img = reader.result;
        };
      }
    },
    // 上传图片
    uploadImg() {
      this.$refs.cropper.getCropBlob(data => {
        let formData = new FormData(); 
        formData.append('id', this.options.id);
        formData.append('img', data);
        uploadFileImg(formData).then(response => {
          this.options.open = false;
          let imgUrl = response.imgUrl;
          this.options.img = process.env.VUE_APP_BASE_API + imgUrl;
          this.getList();
          this.$modal.msgSuccess("上传成功");
          this.options.visible = false;
        });
      });
    },
    // 实时预览
    realTime(data) {
      this.previews = data;
    },
    // 关闭窗口
    closeDialog() {
      this.options.visible = false;
      window.removeEventListener("resize", this.resizeHandler)
    },
    handleOnline(row) {
      // 上架
      if (row.id !== undefined) {
        // 单个
        if(row.url === undefined) {
          this.$modal.msgError('上架视频前必须设置封面图');
          return;
        }
        updateStatus({'id':row.id, 'status':'1'}).then(() => {
          this.$modal.msgSuccess('上架成功');
          this.getList();
        }).catch(() => {});
      } else if (this.ids !== undefined && this.ids.length > 0) {
        batchUpdateStatus({'ids':this.ids, 'status':'1'}).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.msgError("请选中要上架的视频");
      }
    },
    handleOffline(row) {
      // 下架
      if (row.id !== undefined) {
        // 单个
        updateStatus({'id':row.id, 'status':'2'}).then(() => {
          this.$modal.msgSuccess('下架成功');
          this.getList();
        }).catch(() => {});
      } else if (this.ids !== undefined && this.ids.length > 0) {
        batchUpdateStatus({'ids':this.ids, 'status':'2'}).then(response => {
          this.$modal.msgSuccess(response.msg);
          this.getList();
        }).catch(() => {});
      } else {
        this.$modal.msgError("请选中要下架的视频");
      }
    },
  }
}
</script>

<style scoped>
.product_info {
  height: 500px;
  overflow-y: auto;
}
</style>